package com.hinnotek.amoeba.ui.activity.old

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.bean.old.AmeobaCustomerListBean
import com.hinnotek.amoeba.bean.old.AmibaProjectListBean
import com.hinnotek.amoeba.bean.old.AmibaSysUserAdminBean
import com.hinnotek.amoeba.bean.old.PurchaseAddBeanTo
import com.hinnotek.amoeba.databinding.ActivitySellPurchaseRequisitionAddBinding
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.utilities.*
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.lee.common.network.net.ObserverState
import com.lee.common.utils.SharedPreUtils
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SellPurchaseRequisitionAddActivity : BaseActivity<ActivitySellPurchaseRequisitionAddBinding>(), View.OnClickListener {

    private var purchase_type_to: String? = null
    private var customerId = 0
    private var amibaCustomerProjectId = 0
    private var amibaProjectId = 0
    private var approvalUserId = 0
    private var customerName= ""
    private var projectName: String? = null
    private var provideProjectName = ""
    private var approvalUser= ""

    private val viewModel by viewModels<PublicInterfaceViewModel>()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("添加采购申请")

        setContentView(R.layout.activity_sell_purchase_requisition_add)
    }

    override fun initVew() {
        bindingView.etDeliveryDate.setOnClickListener(this)
        bindingView.superButtonSubmit.setOnClickListener(this)
    }

    override fun setData() {
        val orgId= SharedPreUtils.getInteger("orgId",0)
        purchase_type_to = intent.getStringExtra("purchase_type_to")
        if (purchase_type_to == "market" || purchase_type_to == "technology") {


            //请求
            viewModel.getAmibaCustomerListByOrgId(orgId).observe(this,
                object : ObserverState<MutableList<AmeobaCustomerListBean>>() {
                    override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                        val arrayOfStrings = arrayOfNulls<String>(data.size).apply {
                            for (index in data.indices) {
                                this[index] = data[index].customerName
                            }
                        }
                        bindingView.escChooseUser.initAdapter(arrayOfStrings)
                        bindingView.escChooseUser.setOnItemClickListener { parent, view, position, id ->
                            amibaCustomerProjectId = data[position].customerId
                            projectName = data[position].projectName
                        }
                        super.onDataChange(data)
                    }
                })

            //请求
            viewModel.getAmibaCustomerListByOrgId(orgId).observe(this,
                object : ObserverState<MutableList<AmeobaCustomerListBean>>() {
                    override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                        val arrayOfStrings = arrayOfNulls<String>(data.size).apply {
                            for (index in data.indices) {
                                this[index] = data[index].customerName
                            }
                        }
                        bindingView.escRelatedProject.initAdapter(arrayOfStrings)
                        bindingView.escRelatedProject.setOnItemClickListener { parent, view, position, id ->
                            amibaCustomerProjectId = data[position].customerId
                            projectName = data[position].projectName
                        }
                        super.onDataChange(data)
                    }
                })

        } else if (purchase_type_to == "rD") {
            bindingView.llChooseUser.visibility = View.GONE
            //请求
            viewModel.getAmibaProjectListByOrgId(orgId).observe(this,
                object : ObserverState<MutableList<AmibaProjectListBean>>() {
                    override fun onDataChange(data: MutableList<AmibaProjectListBean>) {
                        val arrayOfStrings = arrayOfNulls<String>(data.size).apply {
                            for (index in data.indices) {
                                this[index] = data[index].projectName
                            }
                        }
                        bindingView.escRelatedProject.initAdapter(arrayOfStrings)
                        bindingView.escRelatedProject.setOnItemClickListener { parent, view, position, id ->
                            amibaProjectId = data[position].amibaProjectId
                            provideProjectName = data[position].provideProjectName
                        }
                        super.onDataChange(data)
                    }
                })
        }

        viewModel.getAmibaSysUserAdminByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmibaSysUserAdminBean>>() {
                override fun onDataChange(data: MutableList<AmibaSysUserAdminBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    data.forEachIndexed { index, amountAllocatedBean ->
                        strings[index] = amountAllocatedBean.personName
                    }
                    bindingView.escSellApprover.initAdapter(strings)
                    bindingView.escSellApprover.setOnItemClickListener { _, _, position, id ->
                        approvalUserId = data[position].userId
                        approvalUser = data[position].personName
                    }
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    super.onError(msg, code)
                }
            })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1 -> bindingView.etDeliveryDate.text = data?.getStringExtra("date")
            }
        }
    }

    override fun onClick(v: View) {
        if (ClickUtil.isFastClick()) {
            return
        }
        when (v.id) {
            R.id.et_delivery_date -> IntentUtils.startActivityForResult(
                this,
                MaterialDesignCalendarActivity::class.java,
                null,
                1
            )
            R.id.superButton_submit -> {
                var esc_choose_user_s = ""
                if (purchase_type_to != "rD") {
                    esc_choose_user_s =
                        bindingView.escChooseUser.editText.getText().toString().trim()
                    if (StringUtils.isEmpty(esc_choose_user_s)) {
                        ToastUtils.show(mContext, "请选择客户")
                        return
                    }
                }
                val escRelatedProjectS: String =
                    bindingView.escRelatedProject.editText.getText().toString().trim()
                if (StringUtils.isEmpty(escRelatedProjectS)) {
                    ToastUtils.show(mContext, "请选择项目")
                    return
                }
                val deliveryDate: String =
                    bindingView.etDeliveryDate.getText().toString().trim()
                if (StringUtils.isEmpty(deliveryDate)) {
                    ToastUtils.show(mContext, "请选择日期")
                    return
                }
                val metProjectOverviewS: String =
                    bindingView.metProjectOverview.getContentText().trim()
                if (StringUtils.isEmpty(metProjectOverviewS)) {
                    ToastUtils.show(mContext, "请填写项目概况")
                    return
                }
                val technicalRequirement: String =
                    bindingView.metSkillsRequirement.getContentText().trim()
                if (StringUtils.isEmpty(technicalRequirement)) {
                    ToastUtils.show(mContext, "请填写技术要求")
                    return
                }
                val sellApproverS: String =
                    bindingView.escSellApprover.editText.getText().toString().trim()
                if (StringUtils.isEmpty(sellApproverS)) {
                    ToastUtils.show(mContext, "请选择关联审批人")
                    return
                }

                val purchaseAddBeanTo = PurchaseAddBeanTo(
                    customerId,
                    esc_choose_user_s,
                    amibaCustomerProjectId,
                    escRelatedProjectS,
                    amibaProjectId,
                    provideProjectName,
                    if (bindingView.rbModeY.isChecked()) 1 else 2,
                    deliveryDate,
                    metProjectOverviewS,
                    technicalRequirement,
                    "",
                    approvalUserId,
                    approvalUser,
                    2,
                    "宁创"
                )
                val bundle = Bundle()
                bundle.putSerializable("purchaseAddBeanTo", purchaseAddBeanTo)
                bundle.putString("purchase_type_to", purchase_type_to)
                IntentUtils.startActivity(
                    mContext,
                    SellPurchaseRequisitionSuccessActivity::class.java,
                    bundle
                )
                finishActivity()
            }
        }
    }
}